package com.hcb.tonguetiphealth.view;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.AsyncBitmapLoader;
import com.hcb.tonguetiphealth.manager.Exit;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.widget.homepage.RegisterWidget;

public class AbstractActivity extends Activity {
	protected static Handler mHandler;
	private Handler handler;
	private ProgressDialog messageDialog;
	private String userName;
	private String password;
	private Activity ctx;

	private static final String url = Global.URL + Global.servletLoginOut;
	
    public static void setHandler(Handler handler) {
    	mHandler = handler;
    }
    public static Handler getHandler() {
    	return mHandler;
    }

    public void setActivity(Activity ctx){
    	this.ctx = ctx;
    }
    
	private void exit() {
	/*	DBManager.getInstance(this).release();
		android.os.Process.killProcess(android.os.Process.myPid());*/
		//启动留言jianting
		System.out.println("globaluser:------------+++-"+Global.user.getUserName());
		AbstractActivity.this.startService(Global.serviceLiuYanIntent);
		Global.running = false;
		AbstractActivity.this.stopService(Global.serviceIntent);
		AsyncBitmapLoader.getInstance().clearImageCache();
		Global.clear();

		Exit.close();
	}

	protected void showExitDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("退出系统");
		//builder.setIcon(R.drawable.what);
		builder.setMessage("确定要退出系统？");
		builder.setCancelable(false);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				
				if(Global.user != null) {
					handler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
				} else {
					exit();
				}
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		builder.show();
	}

	@Override
	public void onBackPressed() {
		showExitDialog();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog();
					loginOut();
					break;
				case MessageWhat.DIMISS_DIALOG:
					exit();
					dismissMessageDialog();
					break;
				}
			}
			
		};
	}
	private void loginOut() {
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userId", Global.user.getUserId()));
					response = HttpUtils.Post(url, params);
					
					if(Global.DEBUG) {
						System.out.println("-----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e("loginOut", "Exception", e);
				}
				/*if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					Drinks drinks;
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}*/
				handler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	//--------- 圆形进度条对话框 ------------------------------------------------------------
		private void showMessageDialog() {
			dismissMessageDialog();
			messageDialog = new ProgressDialog(this);
	        messageDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	        messageDialog.setTitle("请稍等");
	        //messageDialog.setIcon(R.drawable.smile);
	        messageDialog.setMessage("正在退出系统...");
	        messageDialog.setCancelable(false);
	        messageDialog.setCanceledOnTouchOutside(false);
	        messageDialog.show();
	    }
		public void showMessageDialog(String msg) {
			dismissMessageDialog();
			messageDialog = new ProgressDialog(this);
	        messageDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	        messageDialog.setTitle("请稍等");
	        //messageDialog.setIcon(R.drawable.smile);
	        messageDialog.setMessage(msg);
	        messageDialog.setCancelable(false);
	        messageDialog.setCanceledOnTouchOutside(false);
	        messageDialog.show();
	    }
		public void dismissMessageDialog() {
	        if (messageDialog != null) {
	            messageDialog.dismiss();
	        }
	    }
		protected void login2() {
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	final AlertDialog dalog = builder.create();
	    	// 获取自定义布局  
	    	LayoutInflater inflater = LayoutInflater.from(this);  
	    	View view = inflater.inflate(R.layout.login_dialog, null);  
	    	final EditText et_userName = (EditText)view.findViewById(R.id.login_dialog_username_et);
	    	final EditText et_password = (EditText)view.findViewById(R.id.login_dialog_password_et);
	    	Button login = (Button)view.findViewById(R.id.login_dialog_login_bt);
	    	Button cancel = (Button)view.findViewById(R.id.login_dialog_cancel_bt);
	    	login.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					userName = et_userName.getText().toString();
	        		password = et_password.getText().toString();
	        		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
	        			Toast.makeText(ctx, "用户名/密码不能为空！" , Toast.LENGTH_LONG).show();
	        		} else {
	        			dalog.dismiss();
	        			doLogin();
	        		}
				}
			});
	    	cancel.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					dalog.dismiss();
				}
			});
//	    	dalog.setTitle("登录");
	    	dalog.setView(view);
	        dalog.show();
		}
		
		protected void login() {
	    	final Dialog waitDialog = new Dialog(this, R.style.TRANSDIALOG);
		    waitDialog.setContentView(R.layout.login_dialog);
		//    waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
		//     waitDialog.setCancelable(false);
		    
		    //设置窗口里控件的透明度
		    Window window = waitDialog.getWindow();
		    WindowManager.LayoutParams wl = window.getAttributes();
		    wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
		    wl.alpha = 0.95f;			//０.０全透明．１.０不透明．
		    window.setAttributes(wl);
	  
	    	final EditText et_userName = (EditText)waitDialog.findViewById(R.id.login_dialog_username_et);
	    	final EditText et_password = (EditText)waitDialog.findViewById(R.id.login_dialog_password_et);
	    	et_userName.setText(userName);
	    	et_password.setText(password);
	    	et_userName.setSelection(userName==null?0:userName.length());
	    	et_password.setSelection(password==null?0:password.length());
	    	Button login = (Button)waitDialog.findViewById(R.id.login_dialog_login_bt);
	    	Button cancel = (Button)waitDialog.findViewById(R.id.login_dialog_cancel_bt);
	    	Button register = (Button)waitDialog.findViewById(R.id.login_dialog_register_bt);
	    	login.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// TODO Auto-generated method stub
					userName = et_userName.getText().toString();
	        		password = et_password.getText().toString();
	        		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
	        			Toast.makeText(ctx, "用户名/密码不能为空！" , Toast.LENGTH_LONG).show();
	        		} else {
	        			waitDialog.dismiss();
	        			doLogin();
	        		}
				}
			});
	    	register.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// TODO Auto-generated method stub
					ctx.setContentView(new RegisterWidget(ctx));
					waitDialog.dismiss();
				}
			});
	    	cancel.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					waitDialog.dismiss();
				}
			});
	    	waitDialog.show();
		}
		
	    private void doLogin() {
	    	mHandler.sendEmptyMessage(MessageWhat.LOGIN);
			new Thread(){
				public void run() {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("username", userName));
					params.add(new BasicNameValuePair("userPassword", password));
					
					String response = HttpUtils.Post(Global.getServletlogin(),
							params);
					if (Global.DEBUG) {
						System.out.println("response" + response);
					}
					if (response != null) {
						try {
							JSONManager jsonManager = new JSONManager();
							if (jsonManager.isGotJSONObject2(response)) {
								User user = new User();
								JSONObject jsonObject = jsonManager.getJsonObject();
								// System.out.println(strReturn+"sucess");
								user.setUserId(jsonObject.getString("userid"));
								user.setUserName(jsonObject.getString("username"));
								user.setImgUrl(jsonObject.getString("headicon"));
								user.setSex(jsonObject.getString("gender"));
								user.setLabels(jsonObject.getString("tags"));
								user.setInfo(jsonObject.getString("intro"));
								user.setLevel(StringUtils.parseFloat(jsonObject.getString("level")));
								user.setProvince(jsonObject.getString("province"));
								user.setCity(jsonObject.getString("city"));
								user.seteMail(jsonObject.getString("email"));
								user.setRealName(jsonObject.getString("truename"));
								user.setTel(jsonObject.getString("mobile"));
								
								Global.user = user;
								mHandler.sendEmptyMessage(MessageWhat.LOGIN_SUCCESS);
							} else {
								Message msg = mHandler.obtainMessage(MessageWhat.LOGIN_FAILD, jsonManager.getMsg());
								msg.sendToTarget();
							}
						} catch (JSONException e) {
							Message msg = mHandler.obtainMessage(MessageWhat.LOGIN_FAILD, "登录失败！");
							msg.sendToTarget();
						}
					} else {
						mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
					}
				}
			}.start();
	    }
	
}
